<template>
  <el-dialog
    :visible.sync="visible"
    top="30px"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :model="data" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="姓名" prop="realName">
        <el-input placeholder="姓名" class="form-control-ml" v-model="data.realName"></el-input>
      </el-form-item>
      <!-- v-if="data.job !== 'org_corp'" -->
      <el-form-item label="部门" prop="deptId">
        <select-dept :clearable="true" class="form-control-ml" v-model="data.deptId"></select-dept>
      </el-form-item>
      <el-form-item label="职务">
        <el-input
          placeholder="职务"
          class="form-control-ml"
          v-model="data.empDescription"
        ></el-input>
      </el-form-item>

      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          placeholder="手机号码"
          class="form-control-ml"
          v-model="data.phoneNumber"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input placeholder="用户名" class="form-control-ml" v-model="data.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" v-if="!type" prop="password">
        <el-input
          type="password"
          placeholder="密码"
          class="form-control-ml"
          v-model="data.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" v-if="!type" prop="password2">
        <el-input
          type="password"
          placeholder="再次输入密码"
          class="form-control-ml"
          v-model="data.password2"
        ></el-input>
      </el-form-item>
      <!-- v-if="data.job !== 'org_corp'" -->
      <el-form-item label="角色" v-if="selectJob" prop="job">
        <select-credit-job
          :clearable="false"
          class="form-control-ml"
          ref="job"
          v-model="data.job"
        ></select-credit-job>
      </el-form-item>
      <el-form-item label="其他权限">
        <select-authority v-model="data.scopes" class="form-control-ml"></select-authority>
      </el-form-item>

      <el-form-item label="所属地">
        <select-address
          v-model="data.addressCode"
          class="form-control-ml"
          auto-top
          placeholder="选择地址"
        ></select-address>
      </el-form-item>
      <el-form-item label="地址详情">
        <el-input
          placeholder="地址详情"
          class="form-control-ml"
          v-model="data.addressDetail"
        ></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input placeholder="身份证号" class="form-control-ml" v-model="data.idCard"></el-input>
      </el-form-item>
      <el-form-item label="身份证照片">
        <ul class="list-inline">
          <li class="list-inline-item">
            <upload-oss
              single-image
              ref="uploadFront"
              accept="image/*"
              :file-list="idImgFront"
              :on-complete="handleUploadFront"
            ></upload-oss>
            <div class="text-muted text-center">身份证正面</div>
          </li>
          <li class="list-inline-item">
            <upload-oss
              single-image
              ref="uploadBack"
              accept="image/*"
              :file-list="idImgBack"
              :on-complete="handleUploadBack"
            ></upload-oss>
            <div class="text-muted text-center">身份证反面</div>
          </li>
        </ul>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-long" @click="onSubmit">保 存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import SelectCreditJob from '@/credit/components/select/SelectCreditJob'
import SelectDept from '@/components/select/SelectDept'
import { getUser, putUser, createUser } from '@/common/api/auth'
import { phoneValidator } from '@/common/plugins/validator'
import SelectAddress from '@/components/select/SelectAddress'
import SelectAuthority from '@/components/select/SelectAuthority'
import { passWordValidator } from '@/common/plugins/validator'
export default {
  components: {
    SelectCreditJob,
    SelectDept,
    SelectAddress,
    SelectAuthority,
  },

  props: {
    visible: Boolean,
    userData: Object,
    userId: String,
  },

  data() {
    let validateName = (rule, value, callback) => {
      if (!/^[0-9a-zA-Z-_()（）]*$/g.test(value)) {
        callback(new Error('用户名只能由英文、数字、下划线组成'))
      } else {
        callback()
      }
    }
    // let validatePhone = (rule, value, callback) => {
    //   if (value === '') {
    //     callback()
    //   } else if (!(/^1[34578]\d{9}$/.test(value))) {
    //     callback(new Error('手机号码有误，请重新输入'))
    //   } else {
    //     callback()
    //   }
    // }
    let validatePass = (rule, value, callback) => {
      if (value !== this.data.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      data: {
        empDescription: '',
        userName: '',
        deptId: '',
        job: '',
        realName: '',
        phoneNumber: '',
        idCard: '',
        idCardImgStr: '',
        idCardImg: '',
        password: '',
        remark: '',
        password2: '',
        jobName: '',
        isApprovalRep: '0',
        isProcessPointBus: '0',
        isProcessPointRisk: '0',
        isReporter: '0',
        isFinancePoint: '0',
        isApprovalSign: '0',
        scopes: [],
      },
      initData: {},
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' },
        ],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phoneNumber: [
          // { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: phoneValidator, trigger: 'blur' },
        ],
        job: [{ required: true, message: '请选择角色', trigger: 'change' }],
        deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          { validator: passWordValidator, trigger: 'blur' },
        ],
        password2: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' },
        ],
      },
      loading: false,
      idImgFront: [],
      idImgBack: [],
      uploadImages: [],
      clientId: '',
    }
  },

  computed: {
    ...mapGetters(['user']),
    selectReporter() {
      return (
        this.data.job === 'org_c_manage' ||
        this.data.job === 'org_c_emp' ||
        this.data.job === 'org_f_manage' ||
        this.data.job === 'org_f_emp'
      )
    },
    id() {
      return this.userId || this.userData ? this.userData.userId : ''
    },
    type() {
      return !!this.id
    },
    selectJob() {
      return !['org_credit_super'].includes(this.data.job)
    },
  },

  watch: {
    userId() {
      this.getData()
    },
    userData: {
      handler: function () {
        this.getData()
      },
      deep: true,
    },
  },

  created() {
    this.initData = { ...this.data }
    this.clientId = this.$store.getters.org.clientId
    this.getData()
  },

  mounted() {},

  methods: {
    getData() {
      if (this.userData) {
        this.initForm(this.userData)
      } else if (this.userId) {
        this.loading = true
        getUser({
          userId: this.userId,
          clientId: this.clientId,
        })
          .then(res => {
            this.initForm(res.data)
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.idImgFront = []
        this.idImgBack = []
      }
    },

    initForm(data) {
      this.data = { ...data }
      if (!this.data.addressCode) {
        this.data.addressCode = this.$utils.getAddressCode()
      }
      if (data.idCardImg) {
        this.idImgFront = [{ url: data.idCardImg[0], name: '' }]
        this.idImgBack = [{ url: data.idCardImg[1], name: '' }]
      } else {
        this.idImgFront = []
        this.idImgBack = []
      }
      this.data.scopes = data.scopes.split('|')
    },

    beforeClose() {
      this.data = { ...this.initData }
      this.$refs.form.clearValidate()
      this.$emit('update:visible', false)
    },

    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$refs.uploadFront.submit()
        } else {
          this.$message.warning('输入错误，请重新输入！')
        }
      })
    },

    handleUploadFront(images) {
      this.uploadImages = [images && images.length ? images[0].url : '']
      this.$refs.uploadBack.submit()
    },

    handleUploadBack(images) {
      this.uploadImages.push(images && images.length ? images[0].url : '')
      if (!this.uploadImages.every(img => img === '')) {
        this.data.idCardImg = `["${this.uploadImages.join('","')}"]`
      }
      if (this.type) {
        this.putUser()
      } else {
        this.postUser()
      }
    },

    putUser() {
      this.loading = true
      let data = {
        orgRegionLever: this.user.orgRegionLever,
        addressCode: this.data.addressCode,
        addressDetail: this.data.addressDetail,
        userName: this.data.userName,
        realName: this.data.realName,
        phoneNumber: this.data.phoneNumber,
        deptId: this.data.deptId,
        job: this.data.job,
        idCard: this.data.idCard,
        idCardImgStr: this.data.idCardImg,
        clientId: this.clientId,
        userId: this.id,
        empDescription: this.data.empDescription,
        scopes: this.data.scopes.join('|'),

        // isApprovalRep: this.data.isApprovalRep,
        // isReporter: this.data.isReporter,
        // isProcessPointBus: this.data.isProcessPointBus,
        // isProcessPointRisk: this.data.isProcessPointRisk,
        // isFinancePoint: this.data.isFinancePoint,
        // isApprovalSign: this.data.isApprovalSign
      }
      if (this.$refs && this.$refs.job) {
        data.jobName = this.$refs.job.getJobName()
      }
      putUser(data)
        .then(() => {
          this.actionSuccess()
          if (this.id === this.user.userId) {
            this.$store.dispatch('getMe')
          }
        })
        .catch(err => {
          this.$message.error(`修改员工账号失败，${err?.data?.errorDescription || ''}`)
        })
        .then(() => {
          this.loading = false
        })
    },

    postUser() {
      let data = {
        orgRegionLever: this.user.orgRegionLever,
        addressCode: this.data.addressCode,
        addressDetail: this.data.addressDetail,
        userName: this.data.userName,
        password: this.data.password,
        realName: this.data.realName,
        phoneNumber: this.data.phoneNumber,
        remark: this.data.remark,
        idCard: this.data.idCard,
        clientId: this.clientId,
        job: this.data.job,
        deptId: this.data.deptId,
        jobName: this.$refs.job.getJobName(),
        idCardImgStr: this.data.idCardImg,
        scopes: this.data.scopes.join('|'),
        empDescription: this.data.empDescription,
        // isApprovalRep: this.data.isApprovalRep,
        // isReporter: this.data.isReporter,
        // isProcessPointBus: this.data.isProcessPointBus,
        // isProcessPointRisk: this.data.isProcessPointRisk,
        // isFinancePoint: this.data.isFinancePoint,
        // isApprovalSign: this.data.isApprovalSign
      }
      this.loading = true
      createUser(data)
        .then(() => {
          this.actionSuccess()
        })
        .catch(err => {
          const message = (err && err.data && err.data.errorDescription) || ''
          this.$message.error(`添加账号账号失败, ${message}！`)
        })
        .then(() => {
          this.loading = false
        })
    },

    actionSuccess() {
      this.$message.success(`${this.type ? '修改' : '添加'}成功！`)
      this.$emit('success', true)
      this.beforeClose()
    },
  },
}
</script>

<style scoped>
.form-sl {
  width: 197px;
}
</style>
